﻿Public Class frmMain

    Dim Server As New ZuneProxy
    Dim DB As ZuneDatabase

    Private artistDirty As Boolean = False
    Private dbDirty As Boolean = False
    Private curArtist As ZuneArtist
    Private curImage As String
    Private curImages As Dictionary(Of String, ZuneImage)

    Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim tmpHeight As Integer
        Dim envLocation As String = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + _
                                    "\Zune Customs\"
        Dim dbFile As String = envLocation + Environment.UserName + ".xml"

        For Each item As ToolStripItem In cntxTray.Items
            tmpHeight += item.Height
        Next

        '//Add artist alphabetic Groups
        For i As Integer = Asc("A") To Asc("Z")
            lvArtists.Groups.Add(Chr(i), Chr(i))
        Next

        '//Load release notes
        If IO.File.Exists(Application.StartupPath + "\rlsnotes.rtf") Then
            richReleaseNotes.LoadFile(Application.StartupPath + "\rlsnotes.rtf")
        End If

        If Not IO.Directory.Exists(envLocation) Then IO.Directory.CreateDirectory(envLocation)

        '//Load default database
        DB = ZuneDatabase.Load(dbFile)

        For Each artist As ZuneArtist In DB.Artists.Values
            With lvArtists.Items.Add(artist.name, artist.name, "")
                .Group = lvArtists.Groups(artist.name.Substring(0, 1).ToUpper)
            End With
        Next

        curImages = New Dictionary(Of String, ZuneImage)

        cntxTray.Height = tmpHeight + 10

        ChangeHeader("Welcome!")
        SwitchPanel(pnlWelcome)

        Server.ClearCache()

        Me.Show()

        If My.Settings.firstStart Then
            MsgBox("This appears to be your first start on this machine." + vbNewLine + _
                   "Please specify the path to your Zune Software in the settings dialog.", MsgBoxStyle.Information, "First Start")
            dlgSettings.ShowDialog()
            My.Settings.firstStart = False
            My.Settings.Save()
        End If

        If My.Settings.startupProxy Then Server.StartServer(DB)
    End Sub

    Private Sub GlobalDisableToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GlobalDisableToolStripMenuItem.Click
        If Server.running Then Server.StopServer() Else Server.StartServer(DB)
    End Sub

    Private Sub ShutdownToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        If Not ShutDownApp(Nothing, Nothing) Then e.Cancel = True
    End Sub

    Private Function ShutDownApp(ByVal sender As Object, ByVal e As System.EventArgs) As Boolean Handles ShutdownToolStripMenuItem.Click
        If dbDirty Then
            Dim msgResult As MsgBoxResult = MsgBox("Do you want to save changes made to the database?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNoCancel, "Save Database?")
            Select Case msgResult
                Case MsgBoxResult.Yes
                    DB.Save()
                Case MsgBoxResult.No
                    'Do nothing but exit
                Case MsgBoxResult.Cancel
                    Return False
            End Select
        End If

        NotifyIcon1.Visible = False
        Server.StopServer()
        My.Settings.Save()
        End
    End Function

    Public Sub ChangeHeader(ByVal newText As String)
        lblHeader.Text = newText
        lblHeader.Location = New Point(Me.Width - lblHeader.ClientSize.Width - 18, lblHeader.Location.Y)
    End Sub

    Private Sub cntxLVArtists_Opening(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles cntxLVArtists.Opening
        RemoveArtistToolStripMenuItem.Enabled = IIf(lvArtists.SelectedItems.Count > 0, True, False)
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        AddArtist()
    End Sub

    Private Sub AddArtistToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AddArtistToolStripMenuItem.Click
        AddArtist()
    End Sub

    Private Sub AddArtist()
        Dim name As String = InputBox("Please enter the Artist's full name", "Add Artist", "Enter here...")
        Dim artist As New ZuneArtist

        If name = "" Then Exit Sub

        artist.name = name
        artist.uuid = ZuneHelpers.GetArtistZuneUUID(name)

        If artist.uuid = "" Then
            artist.uuid = ZuneHelpers.CreateUUID()
            artist.uuidOfficial = False
        Else
            artist.uuidOfficial = True
        End If

        If DB.AddArtist(artist) Then

            With lvArtists.Items.Add(name, name, "")
                .Group = lvArtists.Groups(name.Substring(0, 1).ToUpper)
            End With

        End If

        dbDirty = True
    End Sub

    Private Sub EditArtist(ByVal name As String)
        curArtist = DB.Artists(name)

        txtArtistName.Text = curArtist.name
        txtArtistBio.Text = ZuneHelpers.br2nl(curArtist.biography)
        txtArtistUUID.Text = curArtist.uuid

        lblOfficialUUID.Text = IIf(curArtist.uuidOfficial, "(Official Zune UUID)", "(Non-Official UUID)")
        lblOfficialUUID.ForeColor = IIf(curArtist.uuidOfficial, SystemColors.ControlDark, Color.Firebrick)

        lvArtistImages.Items.Clear()
        curImages.Clear()
        curImage = Nothing

        For Each img As ZuneImage In DB.Images.Values
            If img.artistUUID = curArtist.uuid Then
                ArtistImgLarge.Images.Add(img.URI, img.TempImage)

                With lvArtistImages.Items.Add(img.URI, img.UUID, img.URI)
                    .Tag = img.UUID
                End With

                curImages.Add(img.UUID, img)
            End If
        Next

        ChangeHeader(curArtist.name)
        SwitchPanel(pnlEditArtist)
    End Sub

    Private Sub SaveArtist(ByVal artist As ZuneArtist)
        Dim origName As String = artist.name

        With artist
            .name = txtArtistName.Text
            .biography = ZuneHelpers.nl2br(txtArtistBio.Text)
            .uuid = txtArtistUUID.Text
            .uuidOfficial = lblOfficialUUID.Text.Equals("(Official Zune UUID)")
        End With

        '// Save artist's images
        For Each img As ZuneImage In curImages.Values
            If DB.Images.ContainsKey(img.UUID) Then
                DB.Images(img.UUID) = img
            Else
                DB.Images.Add(img.UUID, img)
            End If
        Next

        DB.Artists.Remove(origName)
        DB.Artists.Add(artist.name, artist)

        lvArtists.Items(origName).Name = artist.name
        lvArtists.Items(artist.name).Text = artist.name

        EditArtist(artist.name)

        Server.ClearCache()
        dbDirty = True
    End Sub

    Private Sub lvArtists_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles lvArtists.DoubleClick
        If lvArtists.SelectedItems.Count > 0 Then _
            EditArtist(lvArtists.SelectedItems(0).Text)
    End Sub

    Public Sub SwitchPanel(ByVal pnl As Panel)
        pnlEditArtist.Visible = False
        pnlWelcome.Visible = False

        pnl.Visible = True
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        Dim result As String

        result = ZuneHelpers.GetArtistZuneUUID(txtArtistName.Text)
        lblOfficialUUID.Text = IIf(result <> "", "(Official Zune UUID)", "(Non-Official UUID)")
        lblOfficialUUID.ForeColor = IIf(result <> "", SystemColors.ControlDark, Color.Firebrick)

        If result = "" Then
            txtArtistUUID.Text = ZuneHelpers.CreateUUID()
        Else
            txtArtistUUID.Text = result
        End If
    End Sub

    Private Sub OKButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OKButton.Click
        If artistDirty Then
            If MsgBox("All non-saved changes will be lost." + vbNewLine + "Are you sure you want to revert?", _
                      MsgBoxStyle.Exclamation And MsgBoxStyle.YesNoCancel, "Revert Artist Info") <> MsgBoxResult.Yes Then Exit Sub
        End If

        EditArtist(curArtist.name)
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SaveArtist(curArtist)
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        Dim dlg As New dlgAddImage
        Dim newImg As New ZuneImage

        If dlg.ShowDialog = Windows.Forms.DialogResult.OK Then
            newImg.URI = dlg.result
            newImg.artistUUID = curArtist.uuid
            newImg.isLocal = dlg.isLocal
            newImg.UUID = ZuneHelpers.CreateUUID()

            ArtistImgLarge.Images.Add(dlg.result, newImg.TempImage)

            With lvArtistImages.Items.Add(dlg.result, newImg.UUID, dlg.result)
                .Tag = newImg.UUID
            End With

            DB.Images.Add(newImg.UUID, newImg)
            curImages.Add(newImg.UUID, newImg)

            lvArtistImages.Items(dlg.result).Selected = True
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If lvArtistImages.SelectedItems.Count = 0 Then Exit Sub

        If MsgBox("Are you sure you want to delete """ + lvArtistImages.SelectedItems(0).Text + """", _
                  MsgBoxStyle.Exclamation + MsgBoxStyle.YesNoCancel, "Delete Image") = MsgBoxResult.Yes Then

            ArtistImgLarge.Images.RemoveByKey(lvArtistImages.SelectedItems(0).ImageKey)
            DB.Images.Remove(lvArtistImages.SelectedItems(0).Text)
            curImages.Remove(lvArtistImages.SelectedItems(0).Text)
            lvArtistImages.Items.Remove(lvArtistImages.SelectedItems(0))
        End If
    End Sub

    Private Sub lvArtistImages_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lvArtistImages.SelectedIndexChanged
        If lvArtistImages.SelectedItems.Count = 0 Then Exit Sub

        '// Load up new data
        curImage = lvArtistImages.SelectedItems(0).Tag

        With curImages(curImage)
            cmbArtistImageType.SelectedIndex = .type
            txtImageURI.Text = .URI
            txtImageUUID.Text = .UUID
        End With
    End Sub

    Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click, lvArtistImages.DoubleClick
        If lvArtistImages.SelectedItems.Count = 0 Then Exit Sub

        Dim client As New Net.WebClient
        Dim previewWnd As New dlgImagePreview

        With previewWnd
            .BackgroundImage = curImages(curImage).TempImage
            .ClientSize = curImages(curImage).TempImage.Size
            .Location = New Point((Screen.PrimaryScreen.Bounds.Width / 2) - (.Size.Width / 2), _
                                  (Screen.PrimaryScreen.Bounds.Height / 2) - (.Size.Height / 2))
        End With

        previewWnd.ShowDialog()
    End Sub

    Private Sub cmbArtistImageType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbArtistImageType.SelectedIndexChanged
        curImages(curImage).type = cmbArtistImageType.SelectedIndex
    End Sub

    Private Sub txtImageURI_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtImageURI.LostFocus
        Dim oldURI As String = curImages(curImage).URI
        ArtistImgLarge.Images.RemoveByKey(curImages(curImage).URI)

        curImages(curImage).URI = txtImageURI.Text
        curImages(curImage).UpdateTemp()

        ArtistImgLarge.Images.Add(curImages(curImage).URI, curImages(curImage).TempImage)
        lvArtistImages.Items(oldURI).Name = curImages(curImage).URI
        lvArtistImages.Items(curImages(curImage).URI).ImageKey = curImages(curImage).URI
    End Sub

    Private Sub ToolStripSplitButton1_ButtonClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripSplitButton1.ButtonClick
        If Server.running Then Server.StopServer() Else Server.StartServer(DB)
    End Sub

    Private Sub StopProxyToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StopProxyToolStripMenuItem1.Click
        If Not Server.running Then Exit Sub

        Server.StopServer()
    End Sub

    Private Sub StartProxyToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartProxyToolStripMenuItem1.Click
        If Server.running Then Exit Sub

        Server.StartServer(DB)
    End Sub

    Private Sub ProxySettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ProxySettingsToolStripMenuItem.Click
        dlgSettings.ShowDialog("proxy")
    End Sub

    Private Sub OptionsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OptionsToolStripMenuItem.Click
        dlgSettings.ShowDialog()
    End Sub

    Private Sub DatabaseTestToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DatabaseTestToolStripMenuItem.Click
        frmZuneDB.Show()
    End Sub

    Private Sub RemoveArtistToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveArtistToolStripMenuItem.Click
        If MsgBox("Are you sure you want to remove Artist """ + lvArtists.SelectedItems(0).Text + """?", MsgBoxStyle.YesNoCancel + MsgBoxStyle.Exclamation, "Remove Artist") = MsgBoxResult.Yes Then
            Dim tmpArtist As ZuneArtist = DB.Artists(lvArtists.SelectedItems(0).Text)
            DB.Artists.Remove(lvArtists.SelectedItems(0).Text)

            For Each img As ZuneImage In DB.Images.Values
                If img.artistUUID = tmpArtist.uuid Then DB.Images.Remove(img.UUID)
            Next

            lvArtists.Items.Remove(lvArtists.SelectedItems(0))
        End If
    End Sub

    Private Sub EditToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EditToolStripMenuItem1.Click
        EditArtist(lvArtists.SelectedItems(0).Text)
        dbDirty = True
    End Sub
End Class
